<template>
    <v-data-table
            v-model="selected"
            :headers="headers"
            :items="dbTables"
            :single-select='false'
            item-key="tableName"
            @input="itemSelected"
            hide-default-footer
            disable-pagination
            show-select
            class="elevation-1">
        <template v-slot:top>
            <v-select v-model="dbSelectValue"
                      :items="dbLinks"
                      item-text="dbName"
                      item-value="id"
                      @change="onDbSelected"
                      label="请选择DB配置"
                      solo
            ></v-select>
        </template>
    </v-data-table>
</template>

<script>
import Databases from '../utils/databases'

export default {
    data () {
        return {
            dbSelectValue: '',
            dbTables:[],   //table内容
            selected: [],  //table选择项目
            dbLinks: [],
            headers: [
                { text: '数据库表名', value: 'tableName' },
                { text: '数据库表描述', value: 'tableComment' }
            ],
            dbPwd:"",
            dbSelected:{}
        }
    },
    created () {
        this.initialize()
    },
    methods:{
        initialize(){
            this.dbLinks = this.$db.get('db_config').value()
        },
        async onDbSelected(value) {
            this.dbPwd = await this.$dialog.prompt({
                text: '密码',
                title: '请输入你选择的数据库的密码',
                actions:{false: '取消', true: '提交'}
            })
            if(this.dbPwd) {//提交有值
                this.dbSelected = this.$db.get('db_config')
                    .find({id: value})
                    .value()
                new Databases(
                    this.dbSelected.dbType,
                    this.dbSelected.dbHost,
                    this.dbSelected.dbPort,
                    this.dbSelected.dbUser,
                    this.dbPwd,
                    this.dbSelected.dbName,
                ).getTableInfo().then(results => {
                    this.dbTables = results
                }).catch(error =>{
                    this.$dialog.error({
                        text: error,
                        title: '出现错误'
                    })
                    this.dbSelectValue = '';
                })
            }else{ //取消之后,清空选项
                this.dbSelectValue = '';
            }
        },
        itemSelected(tables) {
            this.$emit('table-selected',tables,this.dbSelected,this.dbPwd);
        },
        confirmSelect(){
            this.$dialog.confirm({
                text: '请先勾选要生成代码的数据库表',
                actions:{true: '知道了'}
            })
        }
    }
}
</script>